package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order
public class AuthorizeFilter implements GlobalFilter {
    //用户token校验
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否是允许直接访问的请求
        String[] uris={"/login","/sendMsg","/checkCode","/register_auth"};
        //判断请求头是否是允许访问的请求
        for (String s : uris) {
            if (request.getURI().getPath().contains(s)){
                //直接放行
                return chain.filter(exchange);
            }
        }
        //验证是否有token
        String token = request.getHeaders().getFirst("token");
        //如果token为空
        if (StringUtils.isEmpty(token)){
            //放回401给前台
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求
            response.setComplete();
        }
        //token不为空则验证token是否有效
        //获取token里的数据
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //校验token是否过期
            int num = AppJwtUtil.verifyToken(claimsBody);
            //1或2表示token过期
            if (num==1 || num==2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束请求
                return response.setComplete();
            }
        } catch (Exception e) {
            //解析异常 返回401
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求
           return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }
}
